/*
 * This file (RxSharpen.java) is protected by the GNU GPL licence (v2). 
 * Please read the license.txt attached for further informations. 
 * 
 */

package alkwarel.filters;

import java.awt.Color;

import processing.core.PImage;
import alkwarel.objects.AkArtspace;
import alkwarel.objects.RxFilter;

/**
 * Sharpen
 * @author Xavier Gouchet
 *
 */
public class RxSharpen extends RxFilter {

	/**
	 * Standard Constructor.
	 */
	public RxSharpen() {
		super(4006, "Sharpen");
	}

	/**
	 * @see alkwarel.objects.RxFilter#Apply(alkwarel.objects.AkArtspace)
	 */
	public boolean Apply(AkArtspace a) {
		PImage imgx = a.get();
		for (int x=0; x<a.width; x++){
			for (int y=0; y<a.height; y++){
				float redloc   = red(imgx.get(x,y));
				float greenloc = green(imgx.get(x,y)); 
				float blueloc  = blue(imgx.get(x,y)); 

		        float redout = 0; 
		        float greenout = 0; 
		        float blueout = 0;
		        float redtotal = 0;
		        float greentotal = 0;
		        float bluetotal = 0;

		        for (int i=-1; i<2; i++){
		        	for (int j=-1; j<2; j++){
			        	if ( ((x+i)>=0) 
			        			&& ((x+i)<a.width)
			        			&& ((y+j)>=0)
			        			&& ((y+j)<a.height)
			        			&& ((i!=0)||(j!=0))){
			        		redtotal += red(imgx.get(x+i, y+j));
			        		greentotal += green(imgx.get(x+i, y+j));
			        		bluetotal += blue(imgx.get(x+i, y+j));
			        	}
			        }	
		        }
		        
		        redtotal /= 8.0f;
		        greentotal /= 8.0f;
		        bluetotal /= 8.0f;
		        
		        if (redtotal < redloc) redout = 255 - ((redtotal*(256-redloc))/redloc);
		        if (redtotal == redloc) redout = redloc;
		        if (redtotal > redloc) redout = redloc - ((redloc*(redtotal - redloc))/(256-redloc)) ;
		        
		        if (greentotal < greenloc) greenout = 255 - ((greentotal*(256-greenloc))/greenloc);
		        if (greentotal == greenloc) greenout = greenloc;
		        if (greentotal > greenloc) greenout = greenloc - ((greenloc*(greentotal - greenloc))/(256-greenloc)) ;
		        
		        if (bluetotal < blueloc) blueout = 255 - ((bluetotal*(256-blueloc))/blueloc);
		        if (bluetotal == blueloc) blueout = blueloc;
		        if (bluetotal > blueloc) blueout = blueloc - ((blueloc*(bluetotal - blueloc))/(256-blueloc)) ;
		        
		        coulref = new Color((int)redout, (int)greenout, (int)blueout).getRGB();
		        a.set(x,y,coulref);
			}		
		}
		return true;
	}

}
